import java.net.InetSocketAddress;
import java.io.Serializable;

/**
 * The root of the hierarchy of messages which are returned by MulticastQueue.
 *
 * @author Jesper Buus Nielsen, Aarhus University, 2012.
 */
class MulticastMessage implements Serializable, Comparable<MulticastMessage>{
    private InetSocketAddress sender;
    private int timeStamp;
    private int id = UniqueID.getInstance().nextValue();
    private long endTime;
    /** 
     * @param sender The sender of the message.
     */
    MulticastMessage(InetSocketAddress sender) {
	this.sender = sender;
    }
    /**
     * @return The sender of the message.
     */
    public InetSocketAddress getSender() {
	return sender;
    }
    public String toString() {
	return "(MulticastMessage from " + sender + ")";
    }
    
    //Be careful. This might return null if no timeStamp has been set
    public int getTimeStamp(){
    	return timeStamp;
    }
    
    public int getId(){
    	return id;
    }
    
    public void setId(int id){
    	this.id = id;
    }
    
    public void setTimeStamp(int timeStamp){
    	this.timeStamp = timeStamp;
    }
    
    public void setEndTime(long time){
    	endTime = time;
    }
    
    public long getEndTime(){
    	return endTime;
    }
    
    public int compareTo(MulticastMessage other) {
		if (timeStamp == other.timeStamp) {
			int address = sender.getAddress().toString().compareTo(other.sender.getAddress().toString()); 
			if (address == 0) {
				int port = sender.getPort() - other.getSender().getPort();
				if (port == 0) {
					return id - other.getId();
				}
				return port;
			}
			return address;
		}
		return timeStamp - other.timeStamp;
	}
    
	public boolean equals(Object other) {
		if (this == other) return true;
		if (other == null) return false;
		if (getClass() != other.getClass()) return false;
		MulticastMessage o = (MulticastMessage) other;
		return timeStamp == o.getTimeStamp() && 
		sender.getAddress().toString().equals(o.getSender().getAddress().toString()) &&
		sender.getPort() == o.getSender().getPort() &&
		id == o.getId();
	}
}
